package cn.itcast.Servlet;

import cn.itcast.domain.Cake;
import cn.itcast.domain.CakeDB;
import cn.itcast.domain.User;
import cn.itcast.utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取参数
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        HttpSession session = request.getSession();
        User user=null;
        try {
            //获取连接
            Connection conn = JDBCUtils.getConnection();
            //定义sql语句
            String sql="select * from user where username = ? and password = ?";
            //创建pst对象
            PreparedStatement pst=conn.prepareStatement(sql);
            //给？赋值
            pst.setString(1,username);
            pst.setString(2,password);
            //获取查询结果集
            ResultSet rs = pst.executeQuery();
            if (rs.next()){
                user=new User(username,password,rs.getInt("yue"));
            }
            //释放资源
            JDBCUtils.close(conn,pst,rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //如果user不为空
        if (user!=null){
            Collection<Cake> cakes = CakeDB.getAll();
            session.setAttribute("cakes", cakes);
            session.setAttribute("user",user);
            Cookie cookie=new Cookie("autologin",username+"-"+password+"-"+user.getYue());
            cookie.setPath(request.getContextPath());
            cookie.setMaxAge(30 * 60);
            response.addCookie(cookie);
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
        else {
            session.setAttribute("msg","用户名或者密码错误！");
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
